package com.wfh.easychat.aop;

import com.wfh.easychat.annotation.AdminCheckLogin;
import com.wfh.easychat.common.ErrorCode;
import com.wfh.easychat.exception.BusinessException;
import com.wfh.easychat.model.entity.UserInfo;
import com.wfh.easychat.service.UserInfoService;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

/**
 * @Title: CheckLogin
 * @Author wangfenghuan
 * @Package com.wfh.easychat.aop
 * @Date 2025/9/25 20:24
 * @description: 检查是否登录切面
 */
@Aspect
@Component
@Slf4j
@Order(1)
public class AdminCheckLoginInterceptor {

    @Resource
    private UserInfoService userInfoService;

    /**
     * 校验是否登录
     * @param joinPoint
     * @param adminCheckLogin
     * @return
     * @throws Throwable
     */
    @Around("@annotation(adminCheckLogin)")
    public Object doCheckLogin(ProceedingJoinPoint joinPoint, AdminCheckLogin adminCheckLogin) throws Throwable {
        RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = ((ServletRequestAttributes) requestAttributes).getRequest();
        UserInfo loginUser = userInfoService.getLoginUser(request);
        if (loginUser == null){
            throw new BusinessException(ErrorCode.NOT_LOGIN_ERROR);
        }
        // 放行
        return joinPoint.proceed();
    }
}
